import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import localCache from '@/utils/cache'
import { firstMenu } from '@/utils/map-menus'

// 访问项目默认跳转到 main 页面，之后通过路由守卫鉴定当前是否已经登录
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('@/views/main/main.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('@/views/not-found/not-found.vue')
  }
]

const router = createRouter({
  routes,
  history: createWebHashHistory()
})

// 每次跳转的页面不是 login 都要检测当前有没有 token
// 有表示已经登录，相反则表示没有登录会自动跳转到登录页面
router.beforeEach((to) => {
  if (to.path !== '/login') {
    // 不是登录页面都要判断是否已经登录
    const token = localCache.getCache('token')
    // 没有 token 说明没有登录，则跳转到登录页面
    if (!token) return '/login'
  }

  if (to.path === '/main') return firstMenu.url
})

export default router
